import 'package:cached_network_image/cached_network_image.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/utils/double_utils.dart';

import '../entity/banner_for_home_entity.dart';
import '../entity/coin_list_entity.dart';
import '../entity/product_entity.dart';
import '../entity/store_detail_entity.dart';
import '../http/api.dart';
import '../routers/routers.dart';
import '../utils/common_utils.dart';

///
/// 交易首页-区块行情
///
class HomeMarketCoin extends StatefulWidget {
  HomeMarketCoin({Key? key}) : super(key: key);

  @override
  State<HomeMarketCoin> createState() => _HomeMarketCoinState();
}

class _HomeMarketCoinState extends State<HomeMarketCoin> {
  List<CoinListData> datas = [];

  //轮播
  List<BannerForHomeData> banners = [];

  getData() async {
    dynamic result = await Api.coinMarketList();
    CoinListEntity entity = CoinListEntity.fromJson(result);
    setState(() {
      datas.clear();
      if (entity.data.isNotEmpty) {
        datas.addAll(entity.data);
      }
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getBannerList();
    getData();
  }

  getBannerList() async {
    dynamic result = await Api.bannerForHome({'type': 'trade'});
    BannerForHomeEntity entity = BannerForHomeEntity.fromJson(result);
    setState(() {
      banners.clear();
      banners.addAll(entity.data);
      // Future.delayed(const Duration(milliseconds: 1500), () {
      //   setState(() {
      //     isLoopBanner = true;
      //   });
      // });
    });
  }

  getChangeStr(String priceChange) {
    double cha = double.parse(priceChange);
    if (cha > 0) {
      return '+${DoubleUtils.formartNum(cha, 2)}%';
    } else {
      return '${DoubleUtils.formartNum(cha, 2)}%';
    }
  }

  getChangeColor(String priceChange) {
    double cha = double.parse(priceChange);
    if (cha > 0) {
      return Colors.green;
    } else {
      return Colors.red;
    }
  }

  getListItem(int index) {
    return Container(
      height: 110.w,
      margin: EdgeInsets.symmetric(horizontal: 0.w, vertical: 0.w),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Config.colorDivider, width: 2.w),
        ),
      ),
      child: InkWell(
        onTap: () {},
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: Row(
                children: [
                  Container(
                    margin: EdgeInsets.only(left: 5.w, right: 12.w),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(24.w),
                      child: CachedNetworkImage(
                        imageUrl: datas[index].image,
                        fit: BoxFit.fill,
                        width: 48.w,
                        height: 48.w,
                        placeholder: (context, str) {
                          return Image.asset(
                            'assets/images/bg_default_400.png',
                            width: 44.w,
                            height: 44.w,
                            fit: BoxFit.fill,
                          );
                        },
                        errorWidget: (context, url, error) {
                          return Image.asset(
                            'assets/images/bg_default_400.png',
                            width: 48.w,
                            height: 48.w,
                            fit: BoxFit.fill,
                          );
                        },
                      ),
                    ),
                  ),
                  Container(
                    child: Text(
                      datas[index].symbol,
                      softWrap: false,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: (Config.colorText1), fontSize: 28.w),
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: Container(
                alignment: Alignment.center,
                child: Text(
                  datas[index].currentPrice,
                  softWrap: false,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: (Config.colorText1), fontSize: 28.w),
                ),
              ),
            ),
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Container(
                    alignment: Alignment.center,
                    height: 40.w,
                    width: 120.w,
                    decoration: BoxDecoration(
                      color: getChangeColor(datas[index].priceChangePercentage24h),
                      borderRadius: BorderRadius.all(
                        Radius.circular(10.w),
                      ),
                    ),
                    child: Text(
                      getChangeStr(datas[index].priceChangePercentage24h),
                      softWrap: false,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: Config.colorWhite, fontSize: 20.w),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Config.colorBg,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        padding: EdgeInsets.symmetric(horizontal: 25.w),
        // decoration: BoxDecoration(
        //   borderRadius: BorderRadius.circular(12.w),
        // ),
        child: EasyRefresh.builder(
          header: const MaterialHeader(),
          footer: const MaterialFooter(),
          onRefresh: () async {
            await Future.delayed(const Duration(milliseconds: 200), () {
              getBannerList();
              getData();
            });
          },
          // onLoad: () async {},
          childBuilder: (context, physics) {
            return ListView(
              scrollDirection: Axis.vertical,
              physics: physics,
              children: [
                Container(
                  margin: EdgeInsets.only(top: 10.w, bottom: 20.w),
                  //轮播
                  height: 300.w,
                  child: Swiper(
                    itemBuilder: (BuildContext context, int index) {
                      return ClipRRect(
                        borderRadius: BorderRadius.circular(12.w),
                        child: CachedNetworkImage(
                          imageUrl: CommonUtils.compressImageUrl(banners[index].imgPath, 750, 350),
                          fit: BoxFit.fill,
                          width: double.infinity,
                          height: double.infinity,
                          errorWidget: (context, url, error) {
                            return Image.asset(
                              'assets/images/bg_default_400.png',
                              width: double.infinity,
                              height: double.infinity,
                              fit: BoxFit.fill,
                            );
                          },
                        ),
                      );
                    },
                    onTap: (index) {},
                    autoplayDelay: 4000,
                    autoplay: true,
                    loop: true,
                    layout: SwiperLayout.DEFAULT,
                    itemCount: banners.length,
                    // viewportFraction: 0.7,
                    // scale: 0.8,
                    pagination: SwiperPagination(
                      builder: DotSwiperPaginationBuilder(
                          // size: Size(20.w, 4.w),
                          // activeSize: Size(20.w, 4.w),
                          size: 15.w,
                          activeSize: 15.w,
                          activeColor: Config.colorMain,
                          color: Config.colorWhite),
                    ),
                  ),
                ),
                Container(
                  height: 50.w,
                  margin: EdgeInsets.only(top: 0.w),
                  width: double.infinity,
                  padding: EdgeInsets.symmetric(horizontal: 0.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      InkWell(
                        onTap: () {},
                        child: Text(
                          '热门币',
                          style: TextStyle(fontSize: 27.sp, color: Config.colorText1),
                        ),
                      ),
                    ],
                  ),
                ),
                Divider(
                  height: 30.w,
                  thickness: 2.w,
                  color: Config.colorDivider,
                ),
                Container(
                  height: 60.w,
                  margin: EdgeInsets.symmetric(horizontal: 0.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Expanded(
                        child: Text(
                          '币种',
                          style: TextStyle(fontSize: 25.sp, color: Config.colorText3),
                        ),
                      ),
                      Expanded(
                        child: Text(
                          '最新价格(\$)',
                          textAlign: TextAlign.center,
                          style: TextStyle(fontSize: 25.sp, color: Config.colorText3),
                        ),
                      ),
                      Expanded(
                        child: Text(
                          '24H涨跌幅',
                          textAlign: TextAlign.right,
                          style: TextStyle(fontSize: 25.sp, color: Config.colorText3),
                        ),
                      ),
                    ],
                  ),
                ),
                Column(
                  children: [
                    ListView.builder(
                      itemCount: datas.length,
                      shrinkWrap: true,
                      scrollDirection: Axis.vertical,
                      physics: const NeverScrollableScrollPhysics(),
                      itemBuilder: (BuildContext context, int index) {
                        return getListItem(index);
                      },
                    ),
                  ],
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}
